package com.quyunshuo.edwincoffeetwo.common.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.annotation.StringRes
import java.lang.ref.WeakReference

object ToastUtil {

    // 使用弱引用持有 Application Context
    private var contextRef: WeakReference<Context>? = null
    private val handler = Handler(Looper.getMainLooper())

    // 使用独立锁对象保证线程安全
    private val lock = Any()

    /**
     * 必须在 Application 中初始化
     */
    fun init(applicationContext: Context) {
        synchronized(lock) {
            contextRef = WeakReference(applicationContext.applicationContext)
        }
    }

    fun showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
        synchronized(lock) {
            val context = contextRef?.get() ?: return logUninitialized()

            handler.post {
                // 每次创建新 Toast 实例
                Toast.makeText(context, text, duration).apply {
                    show()
                }
            }
        }
    }

    fun showToast(@StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {
        synchronized(lock) {
            val context = contextRef?.get() ?: return logUninitialized()

            handler.post {
                Toast.makeText(context, resId, duration).apply {
                    show()
                }
            }
        }
    }

    private fun logUninitialized() {
        // 这里可以替换为你的日志工具
        println("ToastUtil must be initialized in Application first!")
    }
}